package com.cater.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Functional;
import com.cater.sys.service.impl.FunctionalServiceImpl;
import com.cater.utils.ExcelUtil;
import com.cater.utils.TreeObject;
import com.cater.utils.TreeUtil;
import com.cater.utils.UploadUtil;

/**
 * @author yong
 * @Date 2018年3月23日-上午10:57:20
 * @职能管理控制层
 */
@Controller
@RequestMapping("/functional")
public class FunctionalController {

	@Autowired
	private FunctionalServiceImpl service;

	/**
	 * @职能管理列表视图
	 * @return
	 */
	@RequestMapping("/list")
	public String list() {
		return "sys/functional/list";
	}

	@ResponseBody
	@RequestMapping(value = "/getTrees")
	@SystemControllerLog(description = "职能树形展示")
	public JSONObject getTrees(String nodeid, CommonQuery query) {
		JSONObject json = new JSONObject();
		if (StringUtils.isBlank(nodeid)) {
			nodeid = "0";
		}
		query.setPid(nodeid);
		TreeObject[] rows = TreeUtil.getFunctionalObjects(service.getByPid(query));
		json.put("rows", rows);
		return json;
	}

	/**
	 * @职能管理数据分页
	 * @param query
	 * @param request
	 * @return
	 */
	@RequestMapping("listData")
	@ResponseBody
	@SystemControllerLog(description = "查询职能分页数据")
	public PageResult<Functional> listData(CommonQuery query, HttpServletRequest request) {
		PageResult<Functional> result = service.findPageResult(query);
		return result;
	}

	/**
	 * 添加视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("functional:add")
	public String addView(Model model, CommonQuery query) {
		int sorts = 0;
		if (StringUtils.isNotBlank(query.getLevel())) {
			Functional functional = service.getMaxSort(query);
			if (functional != null) {
				sorts = functional.getSort() + 10;
			} else {
				sorts = 10;
			}
		}
		model.addAttribute("sort", sorts);
		model.addAttribute("parentId", query.getPid());
		model.addAttribute("level", query.getLevel());
		return "sys/functional/add";
	}

	/**
	 * 添加操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("functional:add")
	@ResponseBody
	@SystemControllerLog(description = "添加职能")
	public JSONObject add(Functional t, CommonQuery query) {
		JSONObject json = new JSONObject();
		if (t.getParentId().equals("0")) {
			t.setParentIds(t.getParentId() + "");
			t.setTreeNames(t.getName());
		} else {
			query.setPid(t.getParentId());
			Functional p = service.getByParent(query);
			t.setParentIds(p.getParentIds() + "," + t.getParentId());
			t.setTreeNames(p.getTreeNames() + "/" + t.getName());
		}
		String id = service.saves(t);
		if (StringUtils.isNotBlank(id)) {
			json.put("code", 200);
			json.put("message", "success");
		} else {
			json.put("code", 999);
			json.put("message", "fail");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("functional:edit")
	public String editView(String id, Model model, CommonQuery query) {
		Functional t = service.getById(id);
		model.addAttribute("functional", t);
		return "sys/functional/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("functional:edit")
	@ResponseBody
	@SystemControllerLog(description = "修改职能")
	public JSONObject update(Functional t, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			if (t.getParentId().equals("0")) {
				t.setParentIds(t.getParentId() + "");
				t.setTreeNames(t.getName());
			} else {
				query.setPid(t.getParentId());
				Functional p = service.getByParent(query);
				t.setParentIds(p.getParentIds() + "," + t.getParentId());
				t.setTreeNames(p.getTreeNames() + "/" + t.getName());
			}
			service.update(t);
			json.put("code", 200);
			json.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("functional:delete")
	@SystemControllerLog(description = "删除职能")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			service.delete(id);
			json.put("code", 200);
			json.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	@RequestMapping("inputExcel")
	@ResponseBody
	public JSONObject InputExcel(@RequestParam MultipartFile[] xlsfile, HttpServletRequest request, CommonQuery query) {
		JSONObject json = new JSONObject();
		UploadUtil.fileUpload(xlsfile, "static/upload/", "functional.xls", request);
		String tempid = null;
		String tpid = null;
		// Integer threepid = 0;
		String pid = null;
		String twopid = null;
		try {
			List<List<String>> list2 = ExcelUtil.readExcels("functional.xls", request);
			if (list2 == null || list2.size() == 0) {
				json.put("code", 222);
				return json;
			} else {
				int j = 0;
				int sort = 10;
				int sort2 = 10;
				int sort3 = 10;
				for (List<String> list : list2) {
					Functional t = null;
					if (j > 0) {
						if (list.get(2).equals("0")) {
							t = new Functional();
							tempid = list.get(1);
							t.setId(UUID.randomUUID().toString().replaceAll("-", ""));
							t.setName(list.get(0));
							t.setLevel("1");
							t.setParentId("0");
							t.setParentIds("0");
							t.setTreeNames(list.get(0));
							t.setSort(sort);
							pid = service.saves(t);
							sort2 = 10;
							sort = sort + 10;
						} else if (tempid.equals(list.get(2))) {
							t = new Functional();
							tpid = list.get(1);
							t.setId(UUID.randomUUID().toString().replaceAll("-", ""));
							t.setName(list.get(0));
							t.setLevel("2");
							t.setParentId(pid);
							query.setPid(pid);
							Functional p = service.getByParent(query);
							t.setParentIds(p.getParentIds() + "," + pid);
							t.setTreeNames(p.getTreeNames() + "/" + list.get(0));
							t.setSort(sort2);
							twopid = service.saves(t);
							sort3 = 10;
							sort2 = sort2 + 10;
						} else if (tpid.equals(list.get(2))) {
							t = new Functional();
							t.setId(UUID.randomUUID().toString().replaceAll("-", ""));
							t.setName(list.get(0));
							t.setLevel("3");
							t.setParentId(twopid);
							query.setPid(twopid);
							Functional p = service.getByParent(query);
							t.setParentIds(p.getParentIds() + "," + twopid);
							t.setTreeNames(p.getTreeNames() + "/" + list.get(0));
							t.setSort(sort3);
							service.saves(t);
							sort3 = sort3 + 10;
						}
					}
					j++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			return json;
		}
		json.put("code", 200);
		return json;
	}

	/**
	 * 分配资源页面
	 */
	@RequestMapping(value = "/openZtree")
	public String openauth(HttpServletRequest request, Model model) {
		String ids = request.getParameter("ids");
		if (StringUtils.isNotBlank(ids)) {
			model.addAttribute("ids", ids);
		}
		String tops = request.getParameter("tops");
		if (StringUtils.isNotBlank(tops)) {
			model.addAttribute("tops", tops);
		}
		return "sys/functional/select_functional";
	}

	/**
	 * 分配资源
	 */
	@ResponseBody
	@RequestMapping(value = "/getZtreeJson")
	public List<Map<String, Object>> getZtreeJson(HttpServletRequest request) {
		String ids = request.getParameter("ids");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		List<Functional> functionals = service.getAll();
		for (Functional t : functionals) {
			map = new HashMap<String, Object>();
			map.put("id", t.getId());
			map.put("pId", t.getParentId());
			map.put("name", t.getName());
			if (t.getParentId().equals("0")) {
				map.put("nocheck", true);
			}
			if (t.getLevel().equals("2")) {
				map.put("nocheck", true);
			}
			map.put("open", false);
			if (StringUtils.isNotBlank(ids)) {
				String[] tid = ids.split(",");
				for (String id : tid) {
					if (t.getId().equals(id)) {
						map.put("checked", true);
					}
				}

			}
			list.add(map);
		}
		return list;
	}
}
